/*
 *  ELF object file loading
 *
 *  
 *  Copyright (c) 2010-2011 Tobias Platen
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
 */
#include "dyld_private.h"

int dyld_bootstrap_addr;

ImageLoaderElf::ImageLoaderElf(void* handle,std::string filename,std::string installname)
{
	this->handle=handle;
	this->filename=filename;
	this->installname=installname;
}

int ImageLoaderElf::loadDylibs()
{
	handle=dlopen(filename.c_str(),RTLD_LAZY);
	if(handle==0) DYLD_WARN(printf("could not open native image f%s",filename.c_str()));
	dyld_getsymbol = (void* (*)(char*)) ( dlsym(handle,"dyld_getsymbol"));
	void (*dyld_bootstrap)(void*) = (void (*)(void*)) ( dlsym(handle,"dyld_bootstrap"));
	if(dyld_bootstrap) dyld_bootstrap(&dyld_bootstrap_addr);
	return 0;
}
int ImageLoaderElf::link()
{
	return 0;
}

std::string ImageLoaderElf::getFilename()
{
	return filename;
}
std::string ImageLoaderElf::getInstallname()
{
	return installname;
}
void* ImageLoaderElf::loadThread()
{
	return (void*)0xFFFFFF00;
}

void* ImageLoaderElf::getExportedSymbolAddress(char* name)
{
	void* addr;
	if(handle==NULL) loadDylibs();

	if(dyld_getsymbol)
	{
		addr=dyld_getsymbol(name);
		if(addr) return addr;
	}

	addr= dlsym(handle,name+1);
	printf("DEBUG: %x %s\n",addr,name);
	if(addr) return addr;
	return NULL;
	
	
}
